package com.addtownumbers;

public class AddTowNumbers2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2){
        l1 = reverse(l1);
        l2 = reverse(l2);
        return reverse(toSum(l1,l2));
    }

    private ListNode toSum(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        int carry = 0;
        ListNode dummy = new ListNode(0);
        ListNode prev = dummy;

        while (l1 != null && l2!= null){
            int sum = l1.val + l2.val + carry;
            carry = sum / 10;
            int num = sum % 10;
            ListNode node = new ListNode(num);
            dummy.next = node;
            dummy = dummy.next;

            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null){
            int sum = l1.val + carry;
            carry = sum / 10;
            int num = sum % 10;
            ListNode node = new ListNode(num);
            dummy.next = node;
            dummy = dummy.next;

            l1 = l1.next;
        }
        while (l2 != null){
            int sum = l2.val + carry;
            carry = sum / 10;
            int num = sum % 10;
            ListNode node = new ListNode(num);
            dummy.next = node;
            dummy = dummy.next;

            l2 = l2.next;
        }
        if (carry != 0){
            ListNode node = new ListNode(carry);
            dummy.next = node;
        }

        return prev.next;
    }

    private ListNode reverse(ListNode head) {
        if (head == null) return head;
        ListNode prev = head;
        ListNode current = prev.next;

        prev.next = null;
        while (current != null){
            ListNode next = current.next;

            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }
}
